<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page language="java" import="com.uft.model.entity.*,java.util.List"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ page isELIgnored="false"%>
<script>
	
	$(function () {

		$( "#sName" ).autocomplete({
		      source: function( request, response ) {
		          $.getJSON( '<c:url value="/searchServerList.htm"/>', {
		              term: request.term,
		              name: "serverName"
		            }, response );
		          },
		      minLength: 2
		 });
		$( "#nName" ).autocomplete({
		      source: function( request, response ) {
		          $.getJSON( '<c:url value="/searchServerList.htm"/>', {
		              term: request.term,
		              name: "nodeName"
		            }, response );
		          },
		      minLength: 2
		 });
		
		
		var serverListTable=$('#serverListContainer').jtable({
	        	title: 'Server List',
	            selecting: true,
	            paging: true,
	            pageSize: 10,
	            sorting: true,
	            selectingCheckboxes: true,
	            columnResizable: false,
	            columnSelectable: false,
	            openChildAsAccordion:true,
	            actions: {
	                listAction: '<c:url value="/getServerList.htm"/>'
	            },
	            fields: {
	            	serverId: { key: true,list: false },
	                serverName: { title: 'Server Name'},
	                serverHostname: { title: 'Server Hostname'},
	                nodeName: { title: 'Node Name'},
	                nodeHostname: { title: 'Node Hostname'},
	                status: { 
	                	title: 'Last Known Status',
	                	display: function (data) {
	                		if(data.record.serverRuntime != null){
	                			if(data.record.serverRuntime.status == "RUNNING"){
	                				return $("<img src=<c:url value='/images/16/go-next-5.png'/> title='RUNNING'></img>");
	                			}
	                			if(data.record.serverRuntime.status == "STOPPED"){
	                				return $("<img src=<c:url value='/images/16/media-record-5.png'/> title='STOPPED'></img>");
	                			}
	                			
	                			return $("<img src=<c:url value='/images/16/unknown.gif'/>  title='UNKNOWN'></img>");
	                		}
	                		return $("<img  src=<c:url value='/images/16/unknown.gif'/>  title='UNKNOWN'></img>");
                        }
	                	} 
	             },
	            toolbar: {
	            	items: [
							<sec:authorize ifAllGranted="ROLE_ADMIN">
							{
								 icon: '<c:url value="/images/16/applications-system-3.png"/>',
								 text: 'Settings',
								 click: function () {
									 var $selectedRows = $('#serverListContainer').jtable('selectedRows');
									 if ($selectedRows.length > 0) {
										 $selectedRows.each(function () {
								        	 var record = $(this).data('record');
								        	 var serverId = record.serverId;
								        	 var serverName= record.serverName;
								        	 addServerTabHref(serverId, '<c:url value="getServerSettingsView.htm"/>?serverId='+serverId,"Settings:"+serverName, "Settings");
								        	 
								        });
									 }else{
										 generateDiag("center","error", "Select a Server");
									 }
									 
								 }
							},
							</sec:authorize>
						{
						    icon: '<c:url value="/images/16/info.png"/>',
						    text: 'Info',
						    click: function () {
						        //perform your custom job...
						    	var $selectedRows = $('#serverListContainer').jtable('selectedRows');
						    	 if ($selectedRows.length > 0) {
						    		 $selectedRows.each(function () {
							        	 var record = $(this).data('record');
							        	 var serverId = record.serverId;
							        	 var serverName= record.serverName;
							        	 addServerTabHref(serverId, '<c:url value="getServerInfoView.htm"/>?serverId='+serverId,"Info:"+serverName, "Info");
							        	 
							        });
						    	 } else{
									 generateDiag("center","error", "Select a Server");
								 }
						       
						    }
						},
						{
						    icon: '<c:url value="/images/16/stop.png"/>',
						    text: 'Stop Server',
						    click: function () {
						        //perform your custom job...
						    	var $selectedRows = $('#serverListContainer').jtable('selectedRows');
						    	if ($selectedRows.length <= 0) {
						    		generateDiag("center","error", "Select a Server");
						    	}
						        $selectedRows.each(function () {
						        	 var record = $(this).data('record');
						        	 var id = record.serverId;
						        	 var options = {
	                            			 data: {
	                            			    	serverId: id
	                            			    }, 
	                            			 type: "POST",
	                            			 url: "stopServer.htm",
	                            			 dataType: 'json',
	                            			 global: false,
	                            			 
	                            			 success: function( data ) {
	                            				 if(data.Result == "OK"){
														if(data.Message =="scheduled"){	 
	                            							 uftDeploy.submitNotificationTask(data.UniqueId);
	                            						 }
	                            					 generateDiag("center","success", "Stop Server: "+data.Message);
	                            					 
	                            					 
	                            				 }else{
	                            					 generateDiag("center","Error", "Unable to Schedulre Server Start: "+data.Message);
	                            				 }
	                            			},
	                            			beforeSend: function(){
	                            				waitingDialog({title: "Stop Server", message: "Scheduling Stop Server..."})
	                            			},
	                            			complete: function(){
	                            				closeWaitingDialog();
	                            			}
	                           	 };
	                            	 $.ajaxq("stop",options);
						        });
						    }
						},
	            		{
	                        icon: '<c:url value="/images/16/play.png"/>',
	                        text: 'Start Server',
	                        click: function () {
	                            //perform your custom job...
	                        	var $selectedRows = $('#serverListContainer').jtable('selectedRows');
	                        	if ($selectedRows.length <= 0) {
						    		generateDiag("center","error", "Select a Server");
						    	}
	                            $selectedRows.each(function () {
	                            	 var record = $(this).data('record');
	                            	 var id = record.serverId;
	                            	 var options = {
	                            			 data: {
	                            			    	serverId: id
	                            			    }, 
	                            			 type: "POST",
	                            			 url: "startServer.htm",
	                            			 dataType: 'json',
	                            			 global: false,
	                            			 success: function( data ) {
	                            				 if(data.Result == "OK"){
														if(data.Message =="scheduled"){
	                            						 
	                            							 uftDeploy.submitNotificationTask(data.UniqueId);
	                            						 }
	                            					 generateDiag("center","success", "Start Server: "+data.Message);
	                            					 
	                            					 
	                            				 }else{
	                            					 generateDiag("center","Error", "Unable to Schedulre Server Start: "+data.Message);
	                            				 }
	                            			},
	                            			beforeSend: function(){
	                            				waitingDialog({title: "Start Server", message: "Scheduling Start Server..."})
	                            			},
	                            			complete: function(){
	                            				closeWaitingDialog();
	                            			}
	                            			    
	                            	 };
	                            	 $.ajaxq("start",options);
	                            });
	                        }
	                    },
						{
	                        icon: '<c:url value="/images/16/globe.png"/>',
	                        text: 'Deploy',
	                        click: function () {
	                            //perform your custom job...
	                        	var $selectedRows = $('#serverListContainer').jtable().jtable('selectedRows');
	                        	if ($selectedRows.length <= 0) {
						    		generateDiag("center","error", "Select a Server");
						    	}
	                            $selectedRows.each(function () {
	                            	 var record = $(this).data('record');
	                            	 var serverId = record.serverId;
	                            	 var serverName= record.serverName;
	                            	// alert(serverId);
	                            	 addServerTabHref(serverId, '<c:url value="getDeployViewPage.htm"/>?serverId='+serverId,"Deploy:"+serverName, "Deploy");
	                            });
	                        }
	                    },
	                    {
	                        icon: '<c:url value="/images/16/repeat.png"/>',
	                        text: 'Status',
	                        click: function () {
	                            //perform your custom job...
	                        	var $selectedRows = $('#serverListContainer').jtable('selectedRows');
	                        	if ($selectedRows.length <= 0) {
						    		generateDiag("center","error", "Select a Server");
						    	}
	                            $selectedRows.each(function () {
	                            	 var record = $(this).data('record');
	                            	 var id = record.serverId;
	                            	 var options = {
	                            			 data: {
	                            			    	serverId: id
	                            			    }, 
	                            			 type: "POST",
	                            			 url: "serverStatus.htm",
	                            			 dataType: 'json',
	                            			 global: false,
	                            			 success: function( data ) {
	                            				if(data.Message == "RUNNING"){
	                            					generateDiag("center","success", "Server Status: "+data.Message);
	                            				}else if (data.Message == "RUNNING"){
	                            					generateDiag("center","Warning", "Server Status: "+data.Message);
	                            				}else if (data.Message == "UNKNOWN"){
	                            					generateDiag("center","Warning", "Server Status: "+data.Message);
	                            				}else{
	                            					generateDiag("center","Error", "Server Status: "+data.Message);
	                            				}
	                            				$('#serverListContainer').jtable('load', {
	                            	            	serverName: $('#sName').val(),
	                            	            	nodeName: $('#nName').val()
	                            	            });
                            				},
                            				beforeSend: function(){
	                            				waitingDialog({title: "Start Status", message: "Get Server Status..."});
	                            			},
	                            			complete: function(){
	                            				closeWaitingDialog();
	                            			}
	                            			    
	                            	 };
	                            	 $.ajaxq("status",options);
	                            });
	                        }
	                    }
	            	]
	             }
	        });
		
		 $('#serverListContainer').jtable('load');
		 var serverTabs= $( "#serverTabs" ).tabs({ heightStyle: "fill" }).css({'resize':'none'})
		 $('#LoadRecordsButton').button({
				  icons: {
		                primary: "ui-icon-search"
		              }
			}).click(function (e) {
           		 e.preventDefault();
           		 $('#serverListContainer').jtable('load', {
            		serverName: $('#sName').val(),
            		nodeName: $('#nName').val()
            		});
      		 });
		 $('#refreshButton').button({
			  icons: {
	                primary: "ui-icon-refresh"
	              }
		}).click(function (e) {
	        e.preventDefault();
	        $('#serverListContainer').jtable('load', {
	        	serverName: $('#sName').val(),
	        	nodeName: $('#nName').val()
	        });
		})
	 
	
		function addServerTabHref(id, page, label,action) {
			var tabNameExists = false;	
			var tabTemplate = "<li><a href='{href}'>{label}</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>";
			$('#serverTabs ul li a ').each(function(i) {
				
			    if ($(this).attr( "href" ) == "#"+action+"-"+id) {
			        tabNameExists = true;
			       // console.log(action+"-"+id+" already exits: "+label);
			        //serverTabs.tabs("option", "active", index)
			    }
			});
			if (!tabNameExists){
				var li = $( tabTemplate.replace( /\{href\}/g,  "#"+action+"-"+id ).replace( /\{label\}/g, label ) );
				serverTabs.children( ".ui-tabs-nav" ).append( li );
				$("<div id='"+action+"-" + id + "'>Loading..</div>")
					.appendTo(serverTabs)
					.load(page,  "", function(responseText, textStatus, XMLHttpRequest) {
						 if(textStatus == 'error') {
							 generateDiag("center","Error", responseText, 500, 600);
						 }
					});
				serverTabs.tabs( "refresh" );
				
			}
			var index = $('#serverTabs a[href=\'#'+action+'-'+id+'\']').parent().index(); 
			//console.log("tabindex: "+index)
			$("#serverTabs").tabs("option", "active", index);
			
		}
		serverTabs.delegate( "span.ui-icon-close", "click", function() {
		   var panelId = $( this ).closest( "li" ).remove().attr( "aria-controls" );
		//   console.log(panelId)
		   $( "#" + panelId ).remove();
		   serverTabs.tabs( "refresh" );
		});
		
	});
	
	
</script>


<div id="serverTabs" >
	  <ul>
	    <li><a href="#serverListTab">Server List</a></li>
	  </ul>
	  <div id="serverListTab">
	    <h2>Server List</h2>
	   
		<div class="filtering">
		 	 <form>
		 	 	<table >
		 	 		<tr>
		 	 			<td><label>Node Name: <input type="text" name="nName" id="nName" /></label></td>
		 	 			<td><label>Server Name: <input type="text" name="sName" id="sName" /></label></td>
		 	 			<td valign="bottom"><button id="LoadRecordsButton">Search</button></td>
		 	 			<td valign="bottom"><button id="refreshButton">Refresh</button></td>
		 	 		</tr>
		 	 	</table> 	 	
		 	 </form>
		 	 
		 </div>
		 <div id="serverListContainer"></div>
		
	  </div>
</div>